package cn.yunlang.zhangZhongFei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.yunlang.zhangZhongFei.entity.Goods;
import cn.yunlang.zhangZhongFei.entity.UserCollect;
import cn.yunlang.zhangZhongFei.mapper.GoodsMapper;
import cn.yunlang.zhangZhongFei.mapper.UserCollectMapper;
import cn.yunlang.zhangZhongFei.service.UserCollectService;
import cn.yunlang.zhangZhongFei.vo.request.UserCollectPageVo;
import cn.yunlang.zhangZhongFei.vo.request.UserCollectVo;
import cn.yunlang.zhangZhongFei.vo.response.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户收藏表 服务实现类
 *
 * @author ·
 * @since 2025-05-26 14:50:46
 */
@Service
public class UserCollectServiceImpl extends ServiceImpl<UserCollectMapper, UserCollect>
    implements UserCollectService {

  @Resource private GoodsMapper goodsMapper;

  public R<IPage<UserCollectPageVo>> pageCollect(Integer pageNo, Integer pageSize, Long userId) {
    if (pageNo == null || pageSize == null || userId == null) {
      return R.error(400, "分页参数和用户ID不能为空");
    }
    Page<UserCollect> page =
        this.page(
            new Page<>(pageNo, pageSize),
            new LambdaQueryWrapper<UserCollect>()
                .eq(UserCollect::getUserId, userId)
                .orderByDesc(UserCollect::getCreateTime));
    Page<UserCollectPageVo> pageRes = new Page<>();
    BeanUtils.copyProperties(page, pageRes);
    List<UserCollectPageVo> list = new ArrayList<>();
    List<Long> goodsIdList =
        page.getRecords().stream().map(UserCollect::getCompanyId).collect(Collectors.toList());
    List<Goods> goods = goodsMapper.selectBatchIds(goodsIdList);
    Map<Long, Goods> goodsMap =
        goods.stream().collect(Collectors.toMap(Goods::getId, good -> good));
    page.getRecords()
        .forEach(
            item -> {
              Goods currentGood = goodsMap.get(item.getCompanyId());
              UserCollectPageVo userCollectPageVo = new UserCollectPageVo();
              BeanUtils.copyProperties(item, userCollectPageVo, "createTime");
              if (currentGood != null) {
                BeanUtils.copyProperties(currentGood, userCollectPageVo);
              }
              list.add(userCollectPageVo);
            });
    pageRes.setRecords(list);
    return R.success(pageRes);
  }

  public R<UserCollect> getOne(Long userCollectId) {
    if (userCollectId == null) {
      return R.error(400, "ID不能为空");
    }
    UserCollect userCollect = this.getById(userCollectId);
    if (userCollect == null) {
      return R.error(404, "未找到收藏记录");
    }
    return R.success(userCollect);
  }

  public R<String> doCollect(UserCollectVo userCollectVo) {
    if (userCollectVo == null
        || userCollectVo.getUserId() == null
        || userCollectVo.getCompanyId() == null) {
      return R.error(400, "用户ID和公司ID不能为空");
    }
    UserCollect one =
        this.getOne(
            new LambdaQueryWrapper<UserCollect>()
                .eq(UserCollect::getUserId, userCollectVo.getUserId())
                .eq(UserCollect::getCompanyId, userCollectVo.getCompanyId()));
    boolean back;
    if (one == null) {
      back = this.add(userCollectVo);
    } else {
      back = this.delete(userCollectVo);
    }
    return back ? R.success("操作成功") : R.error(500, "操作失败");
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public boolean add(UserCollectVo userCollectVo) {
    UserCollect userCollect = new UserCollect();
    BeanUtils.copyProperties(userCollectVo, userCollect);
    boolean res = save(userCollect);
    if (res) {
      int update =
          goodsMapper.update(
              new Goods(),
              new LambdaUpdateWrapper<Goods>()
                  .setSql("like_count = like_count + 1")
                  .eq(Goods::getId, userCollectVo.getCompanyId()));
      res = update > 0;
      if (res) {
        return true;
      }
    }
    throw new RuntimeException("收藏失败");
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public boolean delete(UserCollectVo userCollectVo) {
    boolean res =
        remove(
            new LambdaQueryWrapper<UserCollect>()
                .eq(UserCollect::getUserId, userCollectVo.getUserId())
                .eq(UserCollect::getCompanyId, userCollectVo.getCompanyId()));
    if (res) {
      int update =
          goodsMapper.update(
              new Goods(),
              new LambdaUpdateWrapper<Goods>()
                  .setSql("like_count = like_count - 1")
                  .eq(Goods::getId, userCollectVo.getCompanyId()));
      res = update > 0;
      if (res) {
        return true;
      }
    }
    throw new RuntimeException("取消失败");
  }

  public R<String> addCollect(UserCollectVo userCollectVo) {
    if (userCollectVo == null
        || userCollectVo.getUserId() == null
        || userCollectVo.getCompanyId() == null) {
      return R.error(400, "用户ID和公司ID不能为空");
    }
    boolean save = this.add(userCollectVo);
    return save ? R.success("收藏成功") : R.error(500, "收藏失败");
  }

  public R<String> removeCollect(UserCollectVo userCollectVo) {
    if (userCollectVo == null
        || userCollectVo.getUserId() == null
        || userCollectVo.getCompanyId() == null) {
      return R.error(400, "用户ID和公司ID不能为空");
    }
    boolean remove = this.delete(userCollectVo);
    return remove ? R.success("取消成功") : R.error(500, "取消失败");
  }
}
